package com.kabao.javafx.flip;

import javafx.animation.RotateTransition;
import javafx.animation.SequentialTransition;
import javafx.application.Application;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;


public class FlipApp  extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {

        Pane frontPane = new Pane();
        //旋转轴
        frontPane.setRotationAxis(Rotate.Y_AXIS);
        frontPane.setRotate(-90);
        frontPane.setStyle("-fx-background-color: #ccccff");

        Pane backPane = new Pane();
        backPane.setStyle("-fx-background-color: #ffff99;");
        StackPane stackPane = new StackPane(frontPane,backPane);
        stackPane.setMaxSize(160,220);

        stackPane.setOnMouseClicked(mouseEvent->{
            //小于中间，则点击的是左侧，否则点击的是右侧
            dir  = mouseEvent.getX() <= stackPane.getWidth()/2;
            if(backPane.isVisible()){
                flipAnim(frontPane,backPane,dir);
            }else {
                flipAnim(backPane,frontPane,dir);
            }
        });
        Scene scene = new Scene(new BorderPane(stackPane),500,500);
        scene.setCamera(new PerspectiveCamera());
        primaryStage.setScene(scene);
        primaryStage.setTitle("反转");
        primaryStage.show();
    }

    private  boolean fliping;
    private boolean dir;

    private void flipAnim(Pane showPane, Pane hidePane,boolean dir) {
        if(fliping){
            return;
        }
        fliping = true;
        Duration duration = Duration.millis(500);
        //隐藏当前显示的页面
        RotateTransition hideRt = new RotateTransition(duration, hidePane);
        //反转轴
        hideRt.setAxis(Rotate.Y_AXIS);
        hideRt.setFromAngle(0);
        hideRt.setToAngle(dir? 90:-90);
        hideRt.setOnFinished(actionEvent -> {
            hidePane.setVisible(false);
            showPane.setVisible(true);
        });

        //显示刚刚隐藏的页面
        RotateTransition showRt = new RotateTransition(duration, showPane);
        showRt.setAxis(Rotate.Y_AXIS);
        showRt.setFromAngle(dir? -90:90);
        showRt.setToAngle(0);


        SequentialTransition st = new SequentialTransition(hideRt,showRt);
        st.setOnFinished(actionEvent -> fliping = false);
        st.play();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
